/*
 * @Author: yangzonglong
 * @Date: 2021-03-01 13:18:46
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-03-22 18:54:24
 * @Auditor:
 */
import React, { useMemo } from 'react';
import { Form, Input, Tooltip } from 'antd';
import { InputProps as AntdInputProps } from 'antd/lib/input';
import { FormItemProps } from '../components/InputFormItemController';
import { regExpPatterns } from '../../config';
import Qs from 'query-string';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps, ActionFieldType } from './../../interface';
import { QuestionCircleOutlined } from '@ant-design/icons';
import evalScriptText from './../../eval';
import { ShowModalOptionsType } from './../../interface';

interface LinkInputProps extends AntdInputProps {
  bindName?: string;
  initialValue?: string;
  placeholderEn?: string;
}
export interface InputProps extends CanvasItemProps {
  inputProps?: LinkInputProps;
  formItemProps?: FormItemProps;
  disabled?: boolean;
}

const preStyle = { padding: 0, margin: 0 };

const App = (props: InputProps) => {
  const { enviromentConfig, disabled, inputProps, formItemProps, isDesign, domComplete, validateFields, onValuesChange, controlRefs, setActionFiledMap, ...canvasProps } = props;
  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  const rules = useMemo(() => {
    let _rules = formItemProps?.rules ? [...formItemProps?.rules] : [{ required: false }];

    _rules = _rules.map((item: any) => {
      if (item.required) {
        return {
          required: true,
          validator(_: any, value: any) {
            if (!value?.toString()?.trim() || value?.toString()?.trim().length === 0) {
              return Promise.reject(new Error(`${window.$app.t('pleaseEnter')}${localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label}`));
            } else {
              return Promise.resolve();
            }
          }
        };
      }
      return item;
    });

    return formItemProps?.checkRule ? [..._rules, regExpPatterns[formItemProps?.checkRule]] : _rules;
    // eslint-disable-next-line
  }, [formItemProps]);

  const _formItemProps = useMemo(() => {
    return !isDesign && formItemProps?.hideInput ? { ...formItemProps, style: { ...formItemProps?.style, display: 'none' }, hideInput: undefined } : formItemProps;
  }, [formItemProps, isDesign]);

  const _disabled = useMemo(() => {
    if (typeof disabled === 'boolean') return disabled;
    return inputProps?.disabled === undefined ? !!inputProps?.bindName : inputProps?.disabled;
  }, [disabled, inputProps]);

  async function onClick() {
    const query = Qs.parseUrl(window.location.href).query;
    if (_formItemProps?.scriptText) {
      const values = await validateFields?.();

      const refsKey = Object.keys(controlRefs as any);
      const refDataList: any = [];

      if (refsKey.length) {
        for (let item of refsKey) {
          if (controlRefs?.[item]?.onListRefresh) {
            refDataList.push(controlRefs?.[item]);
          }
          refDataList[item] = controlRefs?.[item];
        }
      }

      evalScriptText({
        scriptText: _formItemProps?.scriptText,
        extra: {
          _OBJ1_: values,
          _REFS_: refDataList,
          _QUERY_: query,
          _ENV_: enviromentConfig || {},
          _EVENTS_: props.Events,
          _BUSINESS_: props.business,
          showModal: (options: ShowModalOptionsType) => props.showModal?.(options, props._id),
          showMessage: props.showMessage,
          parentNext: props.parentNext,
          validateRequired: props.validateRequired
        },
        next: (result: any, actionFiled?: ActionFieldType) => {
          onValuesChange((props._id || props.id)!, result || {}, true);

          if (actionFiled) {
            setActionFiledMap?.((prev: ActionFieldType) => {
              return { ...prev, ...actionFiled };
            });
          }
        }
      });
    }
  }

  const label = localStorage.i18nextLng === 'en' ? _formItemProps?.labelEn : _formItemProps?.label;
  const placeholder = localStorage.i18nextLng === 'en' ? inputProps?.placeholderEn : inputProps?.placeholder;
  const tooltip = localStorage.i18nextLng === 'en' ? formItemProps?.tooltipEn : formItemProps?.tooltip ? <span onClick={onClick}>{localStorage.i18nextLng === 'en' ? formItemProps?.tooltipEn : formItemProps?.tooltip}</span> : null;
  const overlayInnerStyle = formItemProps?.tooltipWidth ? { width: formItemProps?.tooltipWidth, cursor: 'pointer' } : {};

  return (
    <Form.Item
      {...canvasProps}
      {..._formItemProps}
      tooltip={undefined}
      rules={rules}
      initialValue={inputProps?.initialValue!}
      label={formItemProps?.showTooltip && (tooltip || _formItemProps?.scriptText) ? <Tooltip overlayInnerStyle={overlayInnerStyle} title={tooltip ? <pre style={preStyle}>{tooltip}</pre> : null}>
        <span>{label}<QuestionCircleOutlined onClick={onClick} style={{ color: '#999', marginLeft: 4, }} /></span>
      </Tooltip> : label}
    >
      <Input
        {...props.inputProps}
        style={{ ...(formItemProps?.style || {}), width: '100%' }}
        placeholder={_disabled ? '' : placeholder}
        disabled={_disabled} />
    </Form.Item>
  );
};

export default App;
